class Solution {
public:
    int n, m;
    vector<vector<bool>> pac, atl;
    vector<vector<int>> ret;
    vector<vector<int>> pacificAtlantic(vector<vector<int>>& heights) {
        n = heights.size(), m = heights[0].size();
        pac = atl = vector<vector<bool>>(n, vector<bool>(m));  //逆向思维，水往高处流
        for (int i = 0; i < n; i++) {
            dfs(i, 0, pac, heights);
            dfs(i, m - 1, atl, heights);
        }
        for (int j = 0; j < m; j++) {
            dfs(0, j, pac, heights);
            dfs(n - 1, j, atl, heights);
        }
        return ret;
    }
    int dx[4] = {-1, 1, 0, 0};
    int dy[4] = {0, 0, -1, 1};
    void dfs(int i, int j, vector<vector<bool>>& num,
             vector<vector<int>>& heights) {
        if (num[i][j]) {
            return;
        }
        num[i][j] = true;
        if (pac[i][j] && atl[i][j]) {
            ret.push_back({i, j});
        }
        for (int k = 0; k < 4; k++) {
            int x = i + dx[k], y = j + dy[k];
            if (x >= 0 && y >= 0 && x < n && y < m &&
                heights[i][j] <= heights[x][y]) {
                dfs(x, y, num, heights);
            }
        }
    }
};